/*
 * Creater:     shizi
 * CreateDate:  2022/03/31
 * Describe：   表单动态渲染
 * */
import React, { Component } from 'react';
import { Form, Row, Col, Input, Radio, Select, DatePicker, Switch, Checkbox, Tag, Upload, message, TimePicker, Cascader, Icon, Tooltip, Button, Drawer, Anchor, Dropdown, Menu, AutoComplete, Divider } from 'antd';
import { Util, dateFormat, dayFormat, timeFormat } from 'tools';
import { $http } from 'containers/config/https';
import { httpConfig } from 'containers/config/httpConfig';
import store from 'store';
import moment from 'moment';
import PublicModalTable from './PublicModalTable';
import RangeDatePicker from 'components/rangePicker/index';
import FindPatients from 'pages/registercard/FindPatients';
import PublicFormDataMaintenance from './PublicFormDataMaintenance';
import FileOnlinePreview from './FileOnlinePreview';
import './style/index.less';

const { Option } = Select;
const { TextArea } = Input;
const { Search } = Input;
const { Link } = Anchor;

/**
  需要传入一个名为 param 的对象，对象包含的参数如下：
  1、formItemCol --- formItem的label和输入域的占比 
    示例：formItemCol={{ labelCol: 8, wrapperCol: 16 }}

  2、rowData --- 回显行数据（Object）

  3、formData --- 表单渲染数据
    示例:
    [{
      dataIndex: 'descripts',
      title: '库存项代码',
      typeCode: 'Input', // 输入框类型
      required: 'Y', // 是否必填
      disabled: 'Y', // 是否可操作
      doubt: '对该描述有疑问'
      col: 8, // 当前formItem的占比 - 比如说一行需要放三个输入域，就占8分（一行为24份）
    }]
*/

class DynamicRenderingForm extends Component {
  constructor() {
    super();
    let userData = React.$getSessionData();
    this.state = {
      userData,
      selectData: {},
      formData: [],
      filterFormData: [],
      rowData: {},
      top: 0,
      left: 0,
      page: 1,
      pageSize: 10,
      modalTableData: [],
      modalTotal: 0,
      modalRowID: '',
      searchDesc: '',
      currentDataIndex: '',
      currentItemData: {},
      modalTableLoading: false,
      modalColumns: [],
      modalTotalWidth: [],
      formatType: {},
      rangeParams: {},
      drawerVisible: false,
      diffData: [], // 字段差异数据
      diffActive: '', // 对比选中数据
      otherInfo: {}, // 其他信息【病人标识】
    };
  }

  componentDidMount() {
    this.props.onRef && this.props.onRef(this);
    // 监听store的变化
    store.subscribe(() => {
      const state = store.getState();
      let diffActive = state.otherData?.DynamicRenderingForm_diffActive;
      if (diffActive !== this.state.diffActive) {
        this.setState({
          diffActive
        })
      }
    })
  }

  static getDerivedStateFromProps(nextProps, prevState) {
    if (JSON.stringify(nextProps.selectData) !== JSON.stringify(prevState.selectData) || JSON.stringify(nextProps.formData) !== JSON.stringify(prevState.formData)) {
      return {
        selectData: nextProps.selectData,
        formData: JSON.parse(JSON.stringify(nextProps.formData)), // 防止重复渲染
        filterFormData: Util.customDeepCopy(nextProps.formData)
      }
    }
    if (JSON.stringify(nextProps.rowData) !== JSON.stringify(prevState.rowData)) {
      return {
        rowData: nextProps.rowData,
        diffActive: '',
        diffData: nextProps.rowData?.diffData || [],
      }
    }
    if (JSON.stringify(nextProps.modalColumns) !== JSON.stringify(prevState.modalColumns)) {
      return {
        modalColumns: nextProps.modalColumns
      }
    }
    if (nextProps.modalTotalWidth !== prevState.modalTotalWidth) {
      return {
        modalTotalWidth: nextProps.modalTotalWidth
      }
    }
    return null
  }

  componentDidUpdate(nextProps, prevState) {
    if (JSON.stringify(prevState.rowData) !== JSON.stringify(this.state.rowData)) { // 弹窗赋值会报错，所以表单在打开弹窗的时候单独调
      this.handleDrawerClose();
      this.handleDataTransformation();
    }
    if ((JSON.stringify(prevState.formData) !== JSON.stringify(this.state.formData)) || (JSON.stringify(prevState.selectData) !== JSON.stringify(this.state.selectData)) || (JSON.stringify(prevState.rowData) !== JSON.stringify(this.state.rowData))) {
      let dataModifyFlag = JSON.stringify(this.state.rowData) === '{}' || JSON.stringify(prevState.rowData) !== JSON.stringify(this.state.rowData);
      // console.log('formData', JSON.stringify(prevState.formData) !== JSON.stringify(this.state.formData));
      // console.log('selectData', JSON.stringify(prevState.selectData) !== JSON.stringify(this.state.selectData));
      // console.log('rowData', JSON.stringify(prevState.rowData) !== JSON.stringify(this.state.rowData));
      // console.log('dataModifyFlag', dataModifyFlag)
      this.handleDefaultAssignment(dataModifyFlag);
    }
  }

  // 数据转化 - 表单赋值前
  handleDataTransformation = () => {
    let { rowData, filterFormData } = this.state;
    if (JSON.stringify(rowData) === '{}') {
      this.resetFields();
    } else {
      let rangeParams = {}; // 日期范围回显
      for (let i = 0; i < filterFormData.length; i++) {
        if (filterFormData[i].typeCode === 'RangePicker') {
          let currentDataIndexArr = filterFormData[i].dataIndex.indexOf('^') > -1 ? filterFormData[i].dataIndex.split('^') : ['startDate', 'endData'];
          for (let j = 0; j < currentDataIndexArr.length; j++) {
            if (rowData[currentDataIndexArr[j]])
              rangeParams[currentDataIndexArr[j]] = rowData[currentDataIndexArr[j]];
          }
        }
      }
      this.setState({ rangeParams });
      let values = this.getDataIndexValues();
      // setTimeout(() => {
      this.setFieldsValue(this.formDataConversion({ ...values }));
      // }, 300)
    }
  }

  // 获取当前表单字段
  getDataIndexValues = () => {
    let { rowData, filterFormData } = this.state;
    let values = {};
    for (var i = 0; i < filterFormData.length; i++) {
      values[filterFormData[i].dataIndex] = undefined;
      for (var keys in rowData) {
        if (filterFormData[i].dataIndex === keys) {
          values[keys] = rowData[keys] !== '' ? rowData[keys] : undefined;
        }
      }
    }
    return values;
  }

  // 表单赋值
  setFieldsValue = (values) => {
    try {
      this.props.form && this.props.form?.setFieldsValue({ ...values });
    } catch (error) {
      console.log(error);
    }
  }

  // 用于循环中调用 - 遍历选择表单数据
  setPromiseFieldsValue = (values) => {
    return new Promise((resolve, reject) => {
      this.setFieldsValue(values);
      resolve();
    })
  }

  // 默认数据源赋值
  handleDefaultAssignment = (dataModifyFlag) => {
    try {
      let { filterFormData, selectData, userData, rowData } = this.state;
      if (filterFormData && Array.isArray(filterFormData) && filterFormData.length > 0) {
        for (let i = 0; i < filterFormData.length; i++) {
          let currentIndex = i;
          filterFormData[i].loading = false;
          filterFormData[i].defaultValue = filterFormData[i]?.defaultValue || filterFormData[i]?.default || undefined;
          let className = filterFormData[i]?.className || '';
          if ('default' in filterFormData[i] && filterFormData[i].default !== '' && (filterFormData[i].typeCode === 'Date' || filterFormData[i].typeCode === 'DatePicker')) { // 默认日期
            let dateNum = filterFormData[i].default && parseInt(filterFormData[i].default) ? moment().subtract(parseInt(filterFormData[i].default), 'days') : moment();
            let defaultDate = moment(dateNum).format(dayFormat);
            filterFormData[i].defaultValue = defaultDate;
          }
          if ((parseInt(filterFormData[i].default) === 0 || filterFormData[i].default === 'currentDate') && (filterFormData[i].typeCode === 'Time' || filterFormData[i].typeCode === 'DateTime')) { // 默认日期时间
            let defaultDateTime = moment().format(filterFormData[i].typeCode === 'DateTime' ? dateFormat : timeFormat);
            filterFormData[i].defaultValue = defaultDateTime;
          }
          if (className === 'disabledDate' && filterFormData[i].typeCode === 'Date') { // 日期选择控制
            let methodName = filterFormData[i].methodName || '<';
            // console.log("methodName", methodName)
            filterFormData[i].disabledDate = (curDate) => {
              return curDate && (methodName === '>' ? curDate > moment().subtract(1, 'days').endOf('day').endOf('day') : ( // 今天之前的开始选择
                methodName === '>=' ? curDate >= moment().endOf('day') : ( // 今天或者今天之前的可以选择
                  methodName === '<' ? curDate < moment().endOf('day') : ( // 今天之后的开始选择
                    methodName === '<=' ? curDate <= moment().subtract(1, 'days').endOf('day') : '')))); // 今天或者今天之后的可以选择
            }
          }
          let checkboxArr = filterFormData[i]?.detailItem?.item || filterFormData[i]?.detailItem || [];
          if ('default' in filterFormData[i] && filterFormData[i].default !== '' && (filterFormData[i].typeCode === 'Switch' || ((filterFormData[i].typeCode === 'Checkbox' || filterFormData[i].typeCode === 'CheckBox') && !(checkboxArr && checkboxArr.length > 0)))) { // 默认开关
            filterFormData[i].defaultValue = filterFormData[i]?.default === 'Y' ? 'Y' : 'N';
          }
          if (filterFormData[i] && (filterFormData[i].typeCode === 'Select' || filterFormData[i].typeCode === 'RadioGroup')) { // 下拉框数据对应取值及数据默认
            let selectDefault = filterFormData[i].default === 'currentHospID' ? userData?.hospID : (filterFormData[i].default === 'currentLocID' ? userData?.locID : (filterFormData[i].default === 'currentUserID' ? userData?.userID : (filterFormData[i]?.default || '')));
            let rowDefault = ''; // 后台下拉数据存在默认值的情况
            if (filterFormData[i].className && selectData) {
              let currentDetailItem = [];
              for (let keys in selectData) {
                if (filterFormData[i].className === keys) {
                  currentDetailItem = selectData[keys];
                  filterFormData[i].detailItem = selectData[keys];
                  break;
                }
              }
              let currentDefaultItem = [];
              if (currentDetailItem && currentDetailItem.length > 0 && selectDefault && selectDefault.indexOf('index-') > -1) { // 默认下标
                let arrIndex = selectDefault.split('index-')[1];
                currentDefaultItem = [currentDetailItem[arrIndex]];
              } else { // 根据后台返回的默认标志默认
                currentDefaultItem = currentDetailItem.filter(item => item.default === 'Y');
              }
              rowDefault = currentDefaultItem && currentDefaultItem.length > 0 ? (currentDefaultItem[0]?.id || undefined) : '';
            }
            let linkValueCodeArr = filterFormData[i] && 'linkValueCode' in filterFormData[i] ? (Array.isArray(filterFormData[i].linkValueCode) ? filterFormData[i].linkValueCode : [filterFormData[i].linkValueCode]) : [];
            let typeCodeSelectFlag = this.getTypeCodeSelectFlag(linkValueCodeArr);
            if (typeCodeSelectFlag && filterFormData[i].linkCode && linkValueCodeArr && linkValueCodeArr.length > 0 && filterFormData[i].dataIndex && rowData[filterFormData[i].dataIndex] && dataModifyFlag) {
              this.handleSelectLinkChange(rowData[filterFormData[i].dataIndex], filterFormData[i], 'return', rowData);
            }
            filterFormData[i].defaultValue = rowDefault || selectDefault || filterFormData[i]?.defaultValue || undefined;
          }
          if (filterFormData[i].typeCode === 'CheckGroup' || filterFormData[i].typeCode === 'CheckBoxGroup') { // 多选框
            let checkDefaultArr = [];
            if (filterFormData[i].className && selectData) {
              let checkDetailItem = [];
              for (let keys in selectData) {
                if (filterFormData[i].className === keys) {
                  checkDetailItem = selectData[keys];
                  filterFormData[i].detailItem = selectData[keys];
                  break;
                }
              }
              if (checkDetailItem && checkDetailItem.length > 0) {
                for (let checkI = 0; checkI < checkDetailItem.length; checkI++) {
                  if (checkDetailItem[checkI].default === 'Y') {
                    checkDefaultArr.push(checkDetailItem[checkI]?.id || '')
                  }
                }
              }
            }
            console.log('checkDefaultArr', checkDefaultArr)
            filterFormData[i].defaultValue = checkDefaultArr;
          }
          if (filterFormData[i] && filterFormData[i].typeCode === 'SearchSelect' && className) { // 回车搜索列表展示
            let baseRecord = filterFormData[i];
            filterFormData[i].valueindex = baseRecord?.descindex || 'descripts'; // 显示在界面上的值 -> 对应下拉数据返回的描述
            filterFormData[i].valueID = baseRecord.methodName; // 需要存到后台的字段对应的id值 - 关联方法
            filterFormData[i].onSearch = (e) => this.handleChargeSearch(e, currentIndex, baseRecord);
          }
          if (filterFormData[i].typeCode && filterFormData[i].typeCode === 'RangePicker' && dataModifyFlag) { // 日期范围
            if (filterFormData[i].className && selectData) {
              let currentDateList = [];
              for (let keys in selectData) {
                if (filterFormData[i].className === keys) {
                  currentDateList = selectData[keys];
                  filterFormData[i].detailItem = selectData[keys];
                  break;
                }
              }
              let currentDefaultItem = currentDateList.filter(item => item.default === 'Y');
              let dateDefaultVal = currentDefaultItem && currentDefaultItem.length > 0 ? currentDefaultItem[0].id : (currentDateList && currentDateList.length > 0 ? currentDateList[0].id : undefined);
              this.state.rangeParams[filterFormData[i]?.methodName || 'dateType'] = dateDefaultVal;
            }
            if (filterFormData[i].dataIndex && filterFormData[i]?.default !== 'none') {
              let dateNum = 'default' in filterFormData[i] && parseInt(filterFormData[i].default) > -1 ? moment().subtract(parseInt(filterFormData[i].default), 'days') : moment();
              let rangeDateSplit = filterFormData[i].dataIndex && filterFormData[i].dataIndex.indexOf('^') > -1 ? filterFormData[i].dataIndex.split('^') : [];
              let startDateIndex = rangeDateSplit.length > 0 ? rangeDateSplit[0] : 'startDate';
              let endDateIndex = rangeDateSplit.length > 0 ? rangeDateSplit[1] : 'endDate';
              this.state.rangeParams[startDateIndex] = moment(dateNum).format(dayFormat);
              this.state.rangeParams[endDateIndex] = moment().format(dayFormat);
            }
          }
          if (className && (filterFormData[i].typeCode === 'Input' || filterFormData[i].typeCode === 'InputNumber')) {
            if (className.indexOf(':') > -1) {
              let classNameSplit = Util.getObjByUrlStr(className);
              // 将关联类中的属性分割处理添加到数据中
              filterFormData[i] = { ...filterFormData[i], ...classNameSplit }
            }
          }
          if (filterFormData[i].default === 'currentHospID') { // 默认当前登录医院
            filterFormData[i].defaultValue = userData?.hospID || undefined;
          }
          if (filterFormData[i].default === 'currentLocID') { // 默认当前科室
            filterFormData[i].defaultValue = userData?.locID || undefined;
          }
          if (filterFormData[i].default === 'currentUserID') { // 默认当前登录人
            filterFormData[i].defaultValue = userData?.userID || undefined;
          }
          if (filterFormData[i].default === 'currentUserDesc') { // 默认当前登录人
            filterFormData[i].defaultValue = userData?.userName || undefined;
          }
          if (filterFormData[i].default === 'empty') { // 空字符串
            filterFormData[i].defaultValue = '';
          }
        }
        this.setState({ filterFormData });
      }
    } catch (error) {
      console.log(error);
    }
  }

  // 判断linkTypeCode中是否包含Select下拉元素
  getTypeCodeSelectFlag = (linkValueCodeArr) => {
    let { filterFormData } = this.state;
    let typeCodeSelectFlag = false;
    for (let j = 0; j < linkValueCodeArr.length; j++) {
      let linkTypeCode = Util.returnDataCccordingToAttributes(filterFormData, linkValueCodeArr[j], 'code')?.typeCode || '';
      if (linkTypeCode === 'Select') {
        typeCodeSelectFlag = true;
        break;
      }
    }
    return typeCodeSelectFlag;
  }

  // 远程搜索事件 
  handleChargeSearch = (value, index, record) => {
    try {
      this.state.filterFormData[index]['loading'] = true;
      this.setState({});
      this.fetchCharge(value, record, (selectData) => {
        this.state.filterFormData[index]['loading'] = false;
        this.state.filterFormData[index]['detailItem'] = selectData;
        this.setState({});
      });
    } catch (error) {
      console.log(error);
    }
  }

  // 获取远程搜索下拉数据
  fetchCharge = (value, record, callback) => {
    console.log('record', record)
    value = value.replace(/^\s+/, '').replace(/\s+$/, '');
    if (!(record && (record?.httpCode || record?.className))) {
      message.error('远程搜索请求接口维护异常！')
      return;
    };
    if (value === '') {
      let resData = [];
      callback(resData);
      return;
    }
    if (this.timeout) {
      clearTimeout(this.timeout);
      this.timeout = null;
    }
    function fakeCharge() {
      let data = {
        params: [{
          [record?.httpDescField || record?.linkCode || 'desc']: value
        }],
        pagination: [{
          pageSize: 200,
          currentPage: 1,
        }]

      }
      $http.post('urlS', this, {
        code: record?.httpCode || record?.className || '',
        data,
        success: function (res) {
          if (res.errorCode === '0') {
            let result = res && 'result' in res && 'rows' in res.result && Array.isArray(res.result.rows) ? res.result.rows : ('result' in res && res.result && 'Data' in res.result && Array.isArray(res.result.Data) ? res.result.Data : (res?.result || res?.manf || []));
            let resultSlice = result && Array.isArray(result) ? result.slice(0, 1000) : [];
            callback(resultSlice);
          }
        }
      });
    }
    this.timeout = setTimeout(fakeCharge, 300);
  }

  handleNormFile = e => {
    if (Array.isArray(e)) {
      return e;
    }
    return e && e.fileList;
  };

  // 渲染form表单
  renderForm = (formData) => {
    const { getFieldDecorator } = this.props.form;
    let { formItemCol } = this.props;
    let { rowData, rangeParams, diffActive } = this.state;
    return formData && formData.filter(item => {
      return !('display' in item && item.display === 'N')
    }).map((childItem, indexChild) => {
      let itemCol = 'formItemCol' in childItem ? childItem.formItemCol : (formItemCol || { labelCol: 8, wrapperCol: 16 });
      let startDateIndex = childItem && childItem.typeCode === 'RangePicker' && childItem.dataIndex && childItem.dataIndex.indexOf('^') > -1 ? childItem.dataIndex.split('^')[0] : 'startDate';
      let endDateIndex = childItem && childItem.typeCode === 'RangePicker' && childItem.dataIndex && childItem.dataIndex.indexOf('^') > -1 ? childItem.dataIndex.split('^')[1] : 'endDate';
      let checkboxArr = childItem?.detailItem?.item || childItem?.detailItem || [];
      let hasMin = 'min' in childItem && childItem?.min !== '' && childItem?.min !== null && childItem?.min !== undefined;
      let hasMax = 'max' in childItem && childItem?.max !== '' && childItem?.max !== null && childItem?.max !== undefined;
      // label处理
      let labelDom = (
        'doubt' in childItem && childItem.doubt ? (
          <span>
            <span className="ellipsis" title={childItem.title}>{childItem.title}</span>
            <Tooltip title={childItem.doubt}>
              <Icon style={{ marginLeft: '4px', color: '#999' }} type="question-circle" />
            </Tooltip>
          </span>
        ) : (
          <span className="ellipsis" title={childItem.title}>{childItem.title}</span>
        )
      );
      return (
        <Col
          key={indexChild}
          style={childItem.style || ''}
          span={parseInt(childItem && childItem.col ? childItem.col : (formItemCol && formItemCol.col ? formItemCol.col : 12))}
        >
          {!childItem.typeCode ? (
            <div style={{ width: '100%', height: childItem.default || '50px' }}>
              {/* 占位 */}
            </div>
          ) : ((childItem.typeCode === 'Switch' || ((childItem.typeCode === 'Checkbox' || childItem.typeCode === 'CheckBox') && !(checkboxArr && checkboxArr.length > 0))) ? ( // 开关
            <Form.Item
              className="drf-form-item"
              label={childItem?.title === 'none' ? '' : labelDom}
              labelCol={{ span: parseInt('labelCol' in childItem ? childItem.labelCol : ('labelCol' in itemCol ? itemCol.labelCol : 12)) }}
              wrapperCol={{ span: parseInt('wrapperCol' in childItem ? childItem.wrapperCol : ('wrapperCol' in itemCol ? itemCol.wrapperCol : 12)) }}
            >
              {getFieldDecorator(childItem.dataIndex, {
                valuePropName: 'checked',
                initialValue: rowData && rowData[childItem.dataIndex] ? (rowData[childItem.dataIndex] === 'Y' ? true : false) : (childItem.defaultValue === 'Y' ? true : false),
                rules: [{ required: childItem.required && childItem.required === 'Y' ? true : false }],
              })(
                this.getInput(childItem, indexChild)
              )}
            </Form.Item>
          ) : (childItem.typeCode === 'Tag' ? (
            <div style={{ paddingLeft: '48px', marginBottom: '12px' }}>
              <Tag style={{ width: '100%', fontSize: '12pt', marginRight: 0 }} color='gold'>{childItem.title + '：' + (this.state[childItem.value] ? this.state[childItem.value] : '')}</Tag>
            </div>
          ) : ((childItem.typeCode === 'Upload' || childItem.typeCode === 'UploadFile' || childItem.typeCode === 'UploadImg') ? ( // 上传
            <Form.Item
              labelCol={{ span: parseInt(childItem.labelCol ? childItem.labelCol : ('labelCol' in itemCol ? itemCol.labelCol : 12)) }}
              wrapperCol={{ span: parseInt(childItem.labelCol ? childItem.wrapperCol : ('wrapperCol' in itemCol ? itemCol.wrapperCol : 12)) }}
              label={childItem?.title === 'none' ? '' : childItem.title}
              extra={childItem.extra ? childItem.extra : ''}
            >
              {getFieldDecorator(childItem.dataIndex, {
                valuePropName: 'fileList',
                initialValue: rowData && rowData[childItem.dataIndex] && Array.isArray(rowData[childItem.dataIndex]) ? rowData[childItem.dataIndex] : (childItem && childItem.defaultValue && Array.isArray(childItem.defaultValue) ? childItem.defaultValue : []),
                rules: [{ required: childItem.required && childItem.required === 'Y' ? true : false }],
                getValueFromEvent: this.handleNormFile,
              })(
                this.getInput(childItem, indexChild)
              )}
            </Form.Item>
          ) : (childItem?.typeCode === 'Text' ? ( // 文本展示
            <Row style={{ height: itemCol.lineHeight ? itemCol.lineHeight : '40px', lineHeight: itemCol.lineHeight ? itemCol.lineHeight : '40px' }}>
              <Col span={parseInt(childItem.labelCol ? childItem.labelCol : (itemCol.labelCol ? itemCol.labelCol : 12))} style={{ height: '100%', textAlign: 'right' }}>
                <span className="ellipsis" style={{ width: '100%', display: 'inline-block', fontWeight: 'normal' }} title={childItem?.title || ''}>
                  {childItem && childItem.title ? childItem.title + '：' : ''}
                </span>
              </Col>
              <Col span={parseInt(childItem.labelCol ? childItem.wrapperCol : (itemCol.wrapperCol ? itemCol.wrapperCol : 12))} style={{ height: '100%' }}>
                <span className="ellipsis" style={{ width: '100%', display: 'inline-block' }} title={this.state.rowData[childItem.dataIndex] || childItem?.defaultValue || ''}>
                  {this.state.rowData[childItem.dataIndex] || childItem?.defaultValue || ''}
                </span>
              </Col>
            </Row>
          ) : (childItem?.typeCode === 'Button' ? ( // 操作按钮
            <Button
              icon={childItem.icon || null}
              ghost={childItem.ghost || false}
              loading={childItem.loading || false}
              className={childItem.className || ''}
              type={childItem.type || 'default'}
              style={{ marginBottom: 'marginBottom' in childItem ? childItem.marginBottom : 16, marginLeft: 'marginLeft' in childItem ? childItem.marginLeft : '', marginTop: 'marginTop' in childItem ? childItem.marginTop : '' }}
              onClick={childItem.onClick || null}
            >
              {childItem.title}
            </Button>
          ) : (childItem?.typeCode === 'RangePicker' ? ( // 日期范围
            <Row className="ant-form-item">
              <Col
                style={{ textAlign: 'right' }}
                className="ant-form-item-label"
                span={parseInt('labelCol' in childItem ? childItem.labelCol : ('labelCol' in itemCol ? itemCol.labelCol : 8))}
              >
                {childItem?.title === 'none' ? '' : (
                  <label className={childItem.required === 'Y' ? 'ant-form-item-required' : ''}>
                    {(childItem && 'linkUrl' in childItem && childItem.linkUrl ? (
                      <Anchor
                        affix={false}
                        className={'drf-anchor' + (childItem.linkUrl === diffActive ? ' drf-anchor-active' : '')}
                        onClick={(e, link) => this.handleShowMarkVisible(childItem, e, link)}
                      >
                        {'doubt' in childItem && childItem.doubt ? (
                          <span>
                            <Link href={childItem.linkUrl} className="drf-label" title={childItem.title} />
                            <Tooltip title={childItem.doubt}>
                              <Icon style={{ marginLeft: '4px', color: '#999' }} type="question-circle" />
                            </Tooltip>
                          </span>
                        ) : (
                          <span>
                            <Link href={childItem.linkUrl} className="drf-label" title={childItem.title} />
                          </span>
                        )}
                      </Anchor>
                    ) : (
                      childItem && 'detailItem' in childItem && childItem.detailItem && childItem.detailItem.length > 0 ? (
                        <Dropdown overlay={(
                          <Menu>
                            {childItem.detailItem.map((rpMenuItem, rpMenuIndex) => {
                              return (
                                <Menu.Item key={rpMenuIndex} onClick={() => this.handleDateFlagChange(childItem?.methodName || 'dateType', rpMenuItem?.id)}>
                                  {rpMenuItem?.descripts || ''}
                                </Menu.Item>
                              )
                            })}
                          </Menu>
                        )}>
                          <span className="span" style={{ color: 'black' }}>
                            {Util.returnDataCccordingToAttributes(childItem?.detailItem || [], rangeParams[childItem?.methodName || 'dateType'], 'id')?.descripts || (childItem?.descripts || '日期选择')}
                            <Icon type="down" style={{ fontSize: '15px', marginLeft: '4px' }} />
                          </span>
                        </Dropdown>
                      ) : (
                        <span>{childItem?.descripts || '日期选择'}</span>
                      )
                    ))}
                  </label>
                )}
              </Col>
              <Col span={parseInt('wrapperCol' in childItem ? childItem.wrapperCol : ('wrapperCol' in itemCol ? itemCol.wrapperCol : 16))}>
                <RangeDatePicker
                  width="300px"
                  format="YYYY-MM-DD"
                  isChange={true}
                  endDate={rangeParams[endDateIndex]}
                  startDate={rangeParams[startDateIndex]}
                  endChange={(e) => this.handleRangeChange(e, endDateIndex)}
                  startChange={(e) => this.handleRangeChange(e, startDateIndex)}
                />
              </Col>
            </Row>
          ) : (childItem?.typeCode === 'Divider' ? (
            <div style={{ padding: '0 4px 0 8px' }}>
              <Divider
                style={{ margin: childItem?.title === 'none' || childItem?.title === 'N' ? '' : '8px 0', fontSize: '13px', color: '#999', fontWeight: 'normal' }}
                orientation={childItem?.className || 'center'} // 显示位置
                dashed={childItem?.linkMethod === 'true' || childItem?.linkMethod === 'Y' ? true : false} // 是否虚线
              >
                {childItem?.title === 'none' || childItem?.title === 'N' ? '' : (childItem?.title || '')}
              </Divider>
            </div>
          ) : (
            <Form.Item
              className={[childItem.typeCode === 'TextArea' ? 'drf-form-textArea-item' : '', 'drf-form-item'].join(' ')}
              label={childItem?.title === 'none' ? '' : (childItem && 'linkUrl' in childItem && childItem.linkUrl ? (
                <Anchor
                  affix={false}
                  className={'drf-anchor' + (childItem.linkUrl === diffActive ? ' drf-anchor-active' : '')}
                  onClick={(e, link) => this.handleShowMarkVisible(childItem, e, link)}
                >
                  {'doubt' in childItem && childItem.doubt ? (
                    <span>
                      <Link href={childItem.linkUrl} className="drf-label" title={childItem.title} />
                      <Tooltip title={childItem.doubt}>
                        <Icon style={{ marginLeft: '4px', color: '#999' }} type="question-circle" />
                      </Tooltip>
                    </span>
                  ) : (
                    <Link href={childItem.linkUrl} className="drf-label" title={childItem.title} />
                  )}
                </Anchor>
              ) : (
                labelDom
              ))}
              style={{ position: 'relative' }}
              labelCol={{ span: parseInt('labelCol' in childItem ? childItem.labelCol : ('labelCol' in itemCol ? itemCol.labelCol : 8)) }}
              wrapperCol={{ span: parseInt('wrapperCol' in childItem ? childItem.wrapperCol : ('wrapperCol' in itemCol ? itemCol.wrapperCol : 16)) }}
              validateStatus={childItem?.typeCode === 'inputNumber' || childItem?.typeCode === 'InputNumber' ? childItem?.validateStatus || undefined : undefined}
              help={childItem?.typeCode === 'inputNumber' || childItem?.typeCode === 'InputNumber' && childItem?.validateStatus === 'error' ? (
                childItem?.errorMsg || (hasMin && hasMax ? ('取值区间：' + (childItem?.min || '') + ' ~ ' + (childItem?.max || '')) : (hasMin ? ('最小录入值为: ' + (childItem?.min || '')) : ('最大录入值为: ' + (childItem?.max || ''))))
              ) : undefined}
            >
              {childItem && 'btnRender' in childItem && childItem.btnRender ? (
                <Row style={{ position: 'initial' }}>
                  <Col span={childItem && 'leftCol' in childItem ? childItem.leftCol : 20}>
                    {getFieldDecorator(childItem.dataIndex, {
                      initialValue: childItem.dataIndex && rowData && JSON.stringify(rowData) !== '{}' ? ( // 编辑
                        childItem.dataIndex in rowData && rowData[childItem.dataIndex] !== undefined && rowData[childItem.dataIndex] !== '' && rowData[childItem.dataIndex] !== null ? (
                          (((childItem.typeCode === 'DateTime' || childItem.typeCode === 'DatePicker' || childItem.typeCode === 'Date' || childItem.typeCode === 'RangePicker' || childItem.typeCode === 'Time') && !(moment.isMoment(rowData[childItem.dataIndex]))) ?
                            moment(rowData[childItem.dataIndex], childItem.typeCode === 'Time' ? timeFormat : ((childItem.typeCode === 'DateTime' || childItem?.showTime) ? dateFormat : dayFormat)) : rowData[childItem.dataIndex])
                        ) : undefined) : ( // 编辑
                        'defaultValue' in childItem && childItem?.defaultValue !== undefined && childItem?.defaultValue !== '' && childItem?.defaultValue !== null ? (
                          ((childItem.typeCode === 'DateTime' || childItem.typeCode === 'DatePicker' || childItem.typeCode === 'Date' || childItem.typeCode === 'RangePicker' || childItem.typeCode === 'Time') && !(moment.isMoment(childItem.defaultValue))) ?
                            moment(childItem.defaultValue, childItem.typeCode === 'Time' ? timeFormat : ((childItem.typeCode === 'DateTime' || childItem?.showTime) ? dateFormat : dayFormat)) : childItem.defaultValue) : undefined),
                      rules: [{ required: childItem.required && childItem.required === 'Y' ? true : false, message: '不能为空' }],
                    })(
                      this.getInput(childItem, indexChild)
                    )}
                  </Col>
                  <Col span={childItem && 'rightCol' in childItem ? childItem.rightCol : 4} style={{ position: 'relative', display: 'block' }}>
                    {childItem.btnRender}
                  </Col>
                </Row>
              ) : (
                getFieldDecorator(childItem.dataIndex, {
                  initialValue: childItem.dataIndex && rowData && JSON.stringify(rowData) !== '{}' ? ( // 编辑
                    childItem.dataIndex in rowData && rowData[childItem.dataIndex] !== undefined && rowData[childItem.dataIndex] !== '' && rowData[childItem.dataIndex] !== null ? (
                      (((childItem.typeCode === 'DateTime' || childItem.typeCode === 'DatePicker' || childItem.typeCode === 'Date' || childItem.typeCode === 'RangePicker' || childItem.typeCode === 'Time') && !(moment.isMoment(rowData[childItem.dataIndex]))) ?
                        moment(rowData[childItem.dataIndex], childItem.typeCode === 'Time' ? timeFormat : ((childItem.typeCode === 'DateTime' || childItem?.showTime) ? dateFormat : dayFormat)) : rowData[childItem.dataIndex])
                    ) : undefined) : ( // 默认值
                    'defaultValue' in childItem && childItem?.defaultValue !== undefined && childItem?.defaultValue !== '' && childItem?.defaultValue !== null ? (
                      ((childItem.typeCode === 'DateTime' || childItem.typeCode === 'DatePicker' || childItem.typeCode === 'Date' || childItem.typeCode === 'RangePicker' || childItem.typeCode === 'Time') && !(moment.isMoment(childItem.defaultValue))) ?
                        moment(childItem.defaultValue, childItem.typeCode === 'Time' ? timeFormat : ((childItem.typeCode === 'DateTime' || childItem?.showTime) ? dateFormat : dayFormat)) : childItem.defaultValue) : undefined),
                  rules: [{ required: childItem.required && childItem.required === 'Y' ? true : false, message: '不能为空' }],
                })(
                  this.getInput(childItem, indexChild)
                )
              )}
            </Form.Item>
          ))))))))}
        </Col>
      )
    })
  }

  // 日期类型切换
  handleDateFlagChange = (dataIndex, val) => {
    this.state.rangeParams[dataIndex] = val;
    this.setState({});
  }

  // 打开痕迹抽屉
  handleShowMarkVisible = (record, e, link) => {
    try {
      e.preventDefault();
      let stortDrawerVisible = store.getState().otherData?.DynamicRenderingForm_drawerVisible || false;
      let diffActive = record.linkUrl || '';
      if (stortDrawerVisible) { // 已经打开过了
        this.handleDiffItemClick(diffActive, 'formLabel');
        return;
      };
      store.dispatch({
        type: 'DynamicRenderingForm_drawerVisible',
        value: true
      });
      this.handleDiffItemClick(diffActive, 'formLabel');
      this.setState({ drawerVisible: true });
    } catch (error) {
      console.log(error)
    }
  }

  // 文件预览
  handleFilePreview = (file) => {
    this.filePreviewRef && this.filePreviewRef.modifyVisible(true, file, file?.filePath || 'file');
  }

  handleBeforeUploadFile = (file, record, index) => {
    const isLt2M = file.size / 1024 / 1024 < 15;
    this.setState({
      isLt2M
    })
    if (!isLt2M) {
      message.error('图片大小不能超过15MB!');
    }
    return false;
  }

  // 上传图片
  handleUploadImgBeforeUpload = (file, record, index) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg';
    if (!isJpgOrPng) {
      message.error('图片格式异常');
      return;
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('图片大小不能超过2MB!');
    }
    return false;
  }

  // 文件上传
  handleUploadFileChange = (info, record, index) => {
    let data = new FormData();
    let currentFile = info?.file || info;
    data.append('file', currentFile);
    const option = {
      method: 'post',
      mode: 'cors',
      headers: {},
      body: data
    };

    let windowHost = window.location && window.location.protocol && window.location.host ? (window.location.protocol + '//' + window.location.host) : (window.location && window.location.origin ? window.location.origin : '');
    let httpUrl = windowHost && (windowHost.indexOf('localhost') !== -1 || windowHost.indexOf('127.0.0.1') !== -1) ? httpConfig.ipDeault : windowHost;
    let uploadUrl = httpUrl + '/uploadFile?fileType=optomefile';
    fetch(uploadUrl, option)
      .then(function (response) {
        if (response.ok) {
          console.log('response', response)
          return response.text();
        } else {
          console.log('网络错误，请稍后再试')
          return;
        }
      }).then((data) => {
        let res = JSON.parse(data);
        if (!(res && 'errorCode' in res)) return;
        let fileList = info?.fileList || [];
        if (res.errorCode === '0') {
          if (fileList && fileList.length > 0) {
            for (var i = 0; i < fileList.length; i++) {
              if (fileList[i].uid === currentFile.uid) {
                fileList[i].filePath = res?.filePath || '';
                break;
              }
            }
          }
          // uploadData[record.dataIndex] = fileList;
          // this.setState({});
          message.success('上传成功');
        } else {
          if (fileList && fileList.length > 0) {
            fileList = fileList.filter(item => item.uid !== currentFile.uid); // 删除上传失败的文件
          }
          message.error(res?.errorMessage || '上传失败');
        }
        record.dataIndex && this.setFieldsValue({
          [record.dataIndex]: fileList
        })
      })
  }

  getInput = (item, index) => {
    let { isEnterJump } = this.props;
    let { formatType } = this.state;
    if (item.typeCode === 'SearchSelect') { // 搜索下拉框
      return (
        <Select
          showSearch
          showArrow={false}
          filterOption={false}
          notFoundContent={null}
          defaultActiveFirstOption={false}
          disabled={item.disabled === 'Y' ? true : false}
          placeholder={item.placeholder ? item.placeholder : ((item.trigger === 'enter' || item.trigger === 'Enter' || item.callback === 'enter' || item.callback === 'Enter') ? '输入关键字回车检索' : '输入关键字检索')}
          loading={item.loading === 'Y' || item.loading === true ? true : false}
          allowClear={item.loading === 'Y' || item.loading === true ? false : true} // 与loading效果互斥
          style={{ width: item && item.width ? (item.width + 'px') : '100%', paddingLeft: 'inputPaddingLeft' in item && item.inputPaddingLeft ? item.inputPaddingLeft : '' }}
          ref={item.onRef || (item.isEnterJump === 'Y' || isEnterJump === 'Y' ? (ref) => this.handleFormItemRef(ref, item.dataIndex) : null)}
          onSearch={(e) => this.handleSelectSearch(item, e)}
          onInputKeyDown={(e) => this.handleSelecttKeyDown(item, e)}
          onSelect={item && item.changeCallBack ? (e) => this.handleChangeCallBack(item.changeCallBack, item.callBackResult, e, item.dataIndex) : (item.onSelect || (item.isEnterJump === 'Y' || isEnterJump === 'Y' ? () => this.handleFormItemPressEnter(item, index) : null))}
        >
          {item.detailItem && Array.isArray(item.detailItem) && item.detailItem.map((childItem, childIndex) => {
            let descripts = 'descindex' in item && item.descindex ? childItem[item.descindex] : childItem.descripts;
            let titleCode = 'desccodeindex' in item && item.descindex ? childItem[item.desccodeindex] : childItem.descriptsSPCode;
            return (
              <Option
                disabled={item && item.disabled === 'Y' ? true : false}
                value={'valueindex' in item && item.valueindex ? childItem[item.valueindex] : childItem.id}
                key={childIndex}
                title={descripts}
                seachprop={descripts + '^' + titleCode}
              >
                {descripts}
              </Option>
            )
          })}
        </Select>
      )
    } else if (item.typeCode === 'Select') { // 下拉框
      let linkValueCodeArr = item && 'linkValueCode' in item ? (Array.isArray(item.linkValueCode) ? item.linkValueCode : [item.linkValueCode]) : [];
      return (
        <Select
          allowClear
          showSearch
          optionFilterProp="seachprop"
          mode={item && item.mode ? item.mode : null} // mode="multiple" 多选
          placeholder={item.placeholder ? (item.placeholder !== 'none' ? item.placeholder : '') : '请选择'}
          ref={item.onRef || (item.isEnterJump === 'Y' || isEnterJump === 'Y' ? (ref) => this.handleFormItemRef(ref, item.dataIndex) : null)}
          style={{ width: item && item.width ? (item.width + 'px') : '100%', paddingLeft: 'inputPaddingLeft' in item && item.inputPaddingLeft ? item.inputPaddingLeft : '' }}
          disabled={item.disabled === 'Y' ? true : false}
          onFocus={item.onFocus || null}
          onClick={item.onClick || null}
          onSelect={item && item.changeCallBack ? (e) => this.handleChangeCallBack(item.changeCallBack, item.callBackResult, e, item.dataIndex, item) : (item.onSelect || (item.isEnterJump === 'Y' || isEnterJump === 'Y' ? () => this.handleFormItemPressEnter(item, index) : null))}
          onChange={linkValueCodeArr && linkValueCodeArr.length > 0 ? (e) => this.handleSelectLinkChange(e, item) : null}
        >
          {item.detailItem && item.detailItem ? React.$SelectOptions(
            item.detailItem,
            'valueindex' in item && item.valueindex ? item.valueindex : 'id',
            'descindex' in item && item.descindex ? item.descindex : 'descripts'
          ) : ''}
        </Select>
      );
    } else if (item.typeCode === 'AutoComplete') { // 自动完成
      return (
        <AutoComplete
          allowClear
          placeholder={item.placeholder ? (item.placeholder !== 'none' ? item.placeholder : '') : '请选择'}
          style={{ width: item && item.width ? (item.width + 'px') : '100%' }}
          defaultActiveFirstOption={false}
          dataSource={item.detailItem && item.detailItem ? React.$SelectOptions(
            item.detailItem,
            'descindex' in item && item.descindex ? item.descindex : 'descripts'
          ) : ''}
          onClick={item.onClick || null}
        >
        </AutoComplete>
      );
    } else if (item.typeCode === 'Cascader') { // 级联选择
      return (
        <Cascader
          placeholder={item.placeholder ? (item.placeholder !== 'none' ? item.placeholder : '') : '请选择'}
          fieldNames={{
            label: item.labelFieldName ? item.labelFieldName : 'descripts',
            value: item.valueFieldName ? item.valueFieldName : 'id',
            children: item.childrenFieldName ? item.childrenFieldName : 'children'
          }}
          disabled={item.disabled === 'Y' ? true : false}
          multiple={item.multiple ? item.multiple : false}
          options={item.options}
          onChange={item && item.changeCallBack ? (e) => this.handleChangeCallBack(item.changeCallBack, item.callBackResult, e, item.dataIndex, item) : null}
        />
      );
    } else if ((item.typeCode === 'inputNumber') || (item.typeCode === 'InputNumber')) { // 数字框
      return (
        <Input
          addonBefore={item?.addonBefore || ''}
          addonAfter={item?.addonAfter || ''}
          placeholder={item.placeholder ? (item.placeholder !== 'none' ? item.placeholder : '') : '请输入'}
          disabled={item.disabled === 'Y' ? true : false}
          style={{
            width: item && item.width ? item.width : ('inputPaddingLeft' in item && item.inputPaddingLeft ? `calc(100% - ${item.inputPaddingLeft})` : '100%'),
            marginLeft: 'inputPaddingLeft' in item && item.inputPaddingLeft ? item.inputPaddingLeft : ''
          }}
          type="number"
          className="input-number"
          ref={item.onRef || (item.isEnterJump === 'Y' || isEnterJump === 'Y' ? (ref) => this.handleFormItemRef(ref, item.dataIndex) : null)}
          onBlur={item.onBlur || null}
          onClick={item.onClick || null}
          onPressEnter={item.onPressEnter || (item.isEnterJump === 'Y' || isEnterJump === 'Y' ? () => this.handleFormItemPressEnter(item, index) : null)}
          onChange={item && item.changeCallBack ? (e) => this.handleChangeCallBack(item.changeCallBack, item.callBackResult, e.target.value, item.dataIndex, item) : null}
        />);
    } else if ((item.typeCode === 'Checkbox') || (item.typeCode === 'CheckBox') || (item.typeCode === 'CheckGroup') || (item.typeCode === 'CheckBoxGroup')) { // 多选框
      let checkboxArr = item?.detailItem?.item || item?.detailItem || [];
      return (
        (item.typeCode === 'CheckGroup') || (item.typeCode === 'CheckBoxGroup') ? (
          <Checkbox.Group
            disabled={item.disabled === 'Y' ? true : false}
            options={checkboxArr && checkboxArr.map(childItem => {
              return {
                disabled: childItem && childItem.disabled ? true : false,
                value: (childItem['valueindex' in item && item.valueindex ? item.valueindex : 'id']),
                label: childItem?.itemValue || (childItem['descindex' in item && item.descindex ? item.descindex : 'descripts'])
              }
            })}
          >
          </Checkbox.Group>
        ) : (
          <Checkbox
            disabled={!!(item.disabled === 'Y')}
            onChange={item && item.changeCallBack ? (e) => this.handleChangeCallBack(item.changeCallBack, item.callBackResult, e.target.checked, item.dataIndex, item) : (item.isEnterJump === 'Y' || isEnterJump === 'Y' ? () => this.handleFormItemPressEnter(item, index) : null)}
          />
        )
      );
    } else if (item.typeCode === 'Switch') { // 开关
      return (
        <Switch
          checkedChildren="是"
          unCheckedChildren="否"
          disabled={item.disabled === 'Y' ? true : false}
          ref={item.onRef || (item.isEnterJump === 'Y' || isEnterJump === 'Y' ? (ref) => this.handleFormItemRef(ref, item.dataIndex) : null)}
          onChange={item && item.changeCallBack ? (e) => this.handleChangeCallBack(item.changeCallBack, item.callBackResult, e, item.dataIndex, item) : (item.isEnterJump === 'Y' || isEnterJump === 'Y' ? () => this.handleFormItemPressEnter(item, index) : null)}
        />
      );
    } else if (item.typeCode === 'Radio' || item.typeCode === 'RadioGroup') { // 单选框
      return (
        <Radio.Group disabled={item.disabled === 'Y' ? true : false} onChange={item?.onPressEnter || null}>
          {(item?.detailItem?.item || item?.detailItem || []).map((childItem, childIndex) => {
            return (
              <Radio value={childItem?.itemID || (childItem['valueindex' in item && item.valueindex ? item.valueindex : 'id'])} key={childIndex}>
                {childItem?.itemValue || (childItem['descindex' in item && item.descindex ? item.descindex : 'descripts'])}
              </Radio>
            )
          })}
        </Radio.Group>
      );
    } else if (item.typeCode === 'DatePicker' || item.typeCode === 'Date' || item?.typeCode === 'DateTime') { // 日期框
      return (
        <DatePicker
          separator="-"
          disabled={item.disabled === 'Y' ? true : false}
          showTime={item && item.showTime ? item.showTime : (item?.typeCode === 'DateTime' ? true : false)}
          disabledDate={item.disabledDate || null} // 限制日期选择
          format={item && (item.showTime || item?.typeCode === 'DateTime') ? (!formatType[item.dataIndex] ? 'YYYY-MM-DD HH:mm:ss' : 'YYYYMMDD HHmmss') : (!formatType[item.dataIndex] ? 'YYYY-MM-DD' : 'YYYYMMDD')}
          style={{ width: item && item.width ? (item.width + 'px') : '100%', paddingLeft: 'inputPaddingLeft' in item && item.inputPaddingLeft ? item.inputPaddingLeft : '' }}
          ref={item.onRef || (item.isEnterJump === 'Y' || isEnterJump === 'Y' ? (ref) => this.handleFormItemRef(ref, item.dataIndex) : null)}
          onChange={item.isEnterJump === 'Y' || isEnterJump === 'Y' ? () => this.handleFormItemPressEnter(item, index) : null}
          onOpenChange={(e) => this.handleOnOpenChangeData(e, item)}
        />
      );
    } else if (item.typeCode === 'Time') { // 时间框
      return (
        <TimePicker
          disabled={item.disabled === 'Y' ? true : false}
          style={{ width: item && item.width ? (item.width + 'px') : '100%', paddingLeft: 'inputPaddingLeft' in item && item.inputPaddingLeft ? item.inputPaddingLeft : '' }}
          onChange={item.isEnterJump === 'Y' || isEnterJump === 'Y' ? () => this.handleFormItemPressEnter(item, index) : null}
          ref={item.onRef || (item.isEnterJump === 'Y' || isEnterJump === 'Y' ? (ref) => this.handleFormItemRef(ref, item.dataIndex) : null)}
        />
      )
    } else if (item.typeCode === 'UploadFile') { // 上传文件
      const uploadButton = (
        <Button disabled={item.disabled === 'Y' ? true : false}>
          <Icon type="upload" /> 点击上传
        </Button>
      );
      return (
        <Upload
          className="avatar-uploader"
          multiple
          listType={item.listType ? item.listType : 'text'}
          beforeUpload={item.beforeUpload ? item.beforeUpload : (e) => this.handleBeforeUploadFile(e, item, index)}
          onChange={(e) => this.handleUploadFileChange(e, item, index)}
          onPreview={this.handleFilePreview}
        >
          {uploadButton}
        </Upload>
      )
    } else if (item.typeCode === 'Upload' || item.typeCode === 'UploadImg') { // 上传图片
      const uploadButton = (
        <div>
          {item.loading ? <Icon type="loading" /> : <Icon type="plus" />}
          <div style={{ marginTop: 8 }}>上传</div>
        </div>
      );
      return (
        <Upload
          className="avatar-uploader"
          showUploadList={false}
          // name={item && item.fileName ? item.fileName : item.title}
          // action={item && item.action ? item.action : ''}
          listType={item.listType ? item.listType : 'picture-card'}
          // onChange={(e) => this.handleUploadChange(e, item && item.onChange ? item.onChange : null)}
          onChange={(e) => this.handleUploadFileChange(e, item, index)}
          beforeUpload={item.beforeUpload ? item.beforeUpload : (e) => this.handleUploadImgBeforeUpload(e, item, index)}
        >
          {item.imageUrl ? <img src={item.imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
        </Upload>
      )
    } else if (item.typeCode === 'TextArea') { // 文本域
      return (
        <TextArea
          allowClear
          autoSize={{ minRows: item?.minRows || item?.className || 2, maxRows: item.maxRows || item?.methodName || 5 }}
          placeholder={item.placeholder ? (item.placeholder !== 'none' ? item.placeholder : '') : '请输入'}
          style={{ width: item && item.width ? (item.width + 'px') : '100%', paddingLeft: 'inputPaddingLeft' in item && item.inputPaddingLeft ? item.inputPaddingLeft : '' }}
          disabled={item.disabled === 'Y' ? true : false}
          onBlur={item.onBlur || null}
          onClick={item.onClick || null}
          ref={item.onRef || (item.isEnterJump === 'Y' || isEnterJump === 'Y' ? (ref) => this.handleFormItemRef(ref, item.dataIndex) : null)}
          onPressEnter={item.onPressEnter || (item.isEnterJump === 'Y' || isEnterJump === 'Y' ? () => this.handleFormItemPressEnter(item, index) : null)}
          onChange={item && item.changeCallBack ? (e) => this.handleChangeCallBack(item.changeCallBack, item.callBackResult, e.target.value, item.dataIndex, item) : null}
        />
      )
    } else if (item.typeCode === 'InputSearch') { // 搜索
      return (
        <Search
          enterButton={item.btnName || '搜索'}
          placeholder={item.placeholder ? item.placeholder : "请输入"}
          style={{
            width: item && item.width ? (item.width + 'px') : ('inputPaddingLeft' in item && item.inputPaddingLeft ? `calc(100% - ${item.inputPaddingLeft})` : '100%'),
            marginLeft: 'inputPaddingLeft' in item && item.inputPaddingLeft ? item.inputPaddingLeft : ''
          }}
          disabled={item.disabled === 'Y' ? true : false}
          onBlur={item.onBlur || null}
          onClick={item.onClick || null}
          onSearch={item.onSearch || null}
          ref={item.onRef || (item.isEnterJump === 'Y' || isEnterJump === 'Y' ? (ref) => this.handleFormItemRef(ref, item.dataIndex) : null)}
          onChange={item && item.changeCallBack ? (e) => this.handleChangeCallBack(item.changeCallBack, item.callBackResult, e.target.value, item.dataIndex) : null}
        />
      )
    } else if (item.typeCode === 'PatSearch') { // 人员标识/人员搜索
      return (
        <Search
          allowClear={!item.loading}
          loading={item.loading}
          placeholder={item.placeholder ? item.placeholder : '病人ID/姓名/身份证号码/手机号码'}
          title="回车触发病人ID查询"
          style={{
            width: item && item.width ? (item.width + 'px') : ('inputPaddingLeft' in item && item.inputPaddingLeft ? `calc(100% - ${item.inputPaddingLeft})` : '100%'),
            marginLeft: 'inputPaddingLeft' in item && item.inputPaddingLeft ? item.inputPaddingLeft : ''
          }}
          disabled={item.disabled === 'Y' ? true : false}
          onBlur={item.onBlur || null}
          onClick={item.onClick || null}
          onChange={(e) => this.handlePatientChange(e, item, index)}
          onSearch={(e) => this.handlePatientSearch(e, item, index)}
          onPressEnter={(e) => this.handlePatientSearch(e.target.value, item, index)}
          ref={item.onRef || (item.isEnterJump === 'Y' || isEnterJump === 'Y' ? (ref) => this.handleFormItemRef(ref, item.dataIndex) : null)}
        />
      )
    } else if (item.typeCode === 'InputTable') { // 回车展示列表，双击选择
      return (
        <Input
          id={item.dataIndex}
          placeholder={item.placeholder ? item.placeholder : '输入关键字回车搜索'}
          style={{
            width: item && item.width ? (item.width + 'px') : ('inputPaddingLeft' in item && item.inputPaddingLeft ? `calc(100% - ${item.inputPaddingLeft})` : '100%'),
            marginLeft: 'inputPaddingLeft' in item && item.inputPaddingLeft ? item.inputPaddingLeft : ''
          }}
          disabled={item.disabled === 'Y' ? true : false}
          onClick={item.onClick || null}
          onChange={this.handleInputTableChang}
          onPressEnter={(e) => this.handleShowTableModal(e, item, index)}
          ref={item.onRef || (item.isEnterJump === 'Y' || isEnterJump === 'Y' ? (ref) => this.handleFormItemRef(ref, item.dataIndex) : null)}
        />
      )
    } else {
      return (
        <Input
          addonBefore={item?.addonBefore || ''}
          addonAfter={item?.addonAfter || ''}
          placeholder={item.placeholder ? (item.placeholder !== 'none' ? item.placeholder : '') : '请输入'}
          style={{
            width: item && item.width ? (item.width + 'px') : ('inputPaddingLeft' in item && item.inputPaddingLeft ? `calc(100% - ${item.inputPaddingLeft})` : '100%'),
            marginLeft: 'inputPaddingLeft' in item && item.inputPaddingLeft ? item.inputPaddingLeft : ''
          }}
          disabled={item.disabled === 'Y' ? true : false}
          ref={item.onRef || (item.isEnterJump === 'Y' || isEnterJump === 'Y' ? (ref) => this.handleFormItemRef(ref, item.dataIndex) : null)}
          onBlur={item.onBlur || null}
          onClick={item.onClick || null}
          onKeyDown={item.onKeyDown || null}
          onPressEnter={item.onPressEnter || (item.isEnterJump === 'Y' || isEnterJump === 'Y' ? () => this.handleFormItemPressEnter(item, index) : null)}
          onDoubleClick={item.onDoubleClick || null}
          onChange={item && item.changeCallBack ? (e) => this.handleChangeCallBack(item.changeCallBack, item.callBackResult, e.target.value, item.dataIndex, item) : null}
        />
      )
    }
  }

  // 搜索框search
  handleSelectSearch = (record, value) => {
    if (!((record && ('trigger' in record && (record.trigger === 'enter' || record.trigger === 'Enter')) || ('callback' in record && (record.callback === 'enter' || record.callback === 'Enter'))))) { // 下拉搜索触发方式为回车不自动触发查询
      record && record.onSearch && record.onSearch(value);
    }
  }

  // 搜索框键盘事件
  handleSelecttKeyDown = (record, e) => {
    if (e.keyCode == '13') {
      record && record.onSearch && record.onSearch(e.target.value);
    }
  }

  // 日期选择
  handleRangeChange = (value, dataIndex) => {
    let { rangeParams } = this.state;
    if (dataIndex) {
      rangeParams[dataIndex] = value;
      this.setState({});
    }
  }

  //日期面板打开/关闭
  handleOnOpenChangeData = (status, record) => {
    this.state.formatType[record.dataIndex] = !!status;
    this.setState({});
  }

  handleFormItemRef = (ref, dataIndex) => {
    this[dataIndex] = ref;
  }

  // 回车切换下一个
  handleFormItemPressEnter = (record, index) => {
    let { filterFormData } = this.state;
    if (record && 'jumpID' in record && record.jumpID) {
      let nextID = Util.returnDataCccordingToAttributes(filterFormData, record.jumpID, 'id')?.id; // 获取维护对应跳转输入域的下标
      for (var i = 0; i < filterFormData.length; i++) {
        if (filterFormData[i].id === nextID) {
          index = i;
          break;
        }
      }
    } else {
      index += 1;
    }
    let nextDataIndex = this.getNextDataIndex(index);
    nextDataIndex && this[nextDataIndex]?.focus();
  }

  // 回车获取下一个可跳转的输入域
  getNextDataIndex = (index) => {
    let { filterFormData } = this.state;
    if (filterFormData && (filterFormData.length > index)) {
      let formItem = filterFormData[index];
      if (!(formItem && 'disabled' in formItem && formItem.disabled === 'Y')) {
        return formItem?.dataIndex || '';
      } else {
        return this.getNextDataIndex(index + 1);
      }
    } else {
      return '';
    }
  }

  getBase64 = (img, callback) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
  }

  // 图片上传change事件
  handleUploadChange = (info, callback) => {
    if (info.file.status === 'uploading' || info.file.status === 'error') {
      callback && callback(info.file.status);
      return;
    }
    if (info.file.status === 'done') {
      // Get this url from response in real world.
      getBase64(info.file.originFileObj, imageUrl => {
        callback && callback('done', imageUrl);
      });
    }
  };

  // change事件回调赋值
  handleChangeCallBack = (callBack, callBackDataIndex, e, dataIndex, item) => {
    // 根据传入进来的方法修改当前数据的callBackDataIndex字段value
    let fieldsValue = this.props.form.getFieldsValue();
    if (!callBackDataIndex) return;
    if (callBackDataIndex === 'Fn' || callBackDataIndex.indexOf('Fn') > -1) { // 直接回调函数
      callBack && callBack(e, dataIndex, {
        ...this.formDataFormatConversion(fieldsValue),
        [dataIndex]: e,
        callBackResult: callBackDataIndex
      });
      return;
    }
    if (callBackDataIndex === 'inputNumber' || callBackDataIndex === 'InputNumber') { // 数字输入框判断输入范围
      if ((item?.typeCode === 'inputNumber' || item?.typeCode === 'InputNumber') && (item?.max || item?.min)) { // 输入域范围，只针对于数字框
        let hasMin = 'min' in item && item.min !== '' && item.min !== null && item.min !== undefined;
        let hasMax = 'max' in item && item.max !== '' && item.max !== null && item.max !== undefined;
        let isValidMin = hasMin && e >= Number(item?.min);
        let isValidMax = hasMax && e <= Number(item?.max);
        if (hasMin && hasMax) {
          item.validateStatus = isValidMin && isValidMax ? 'success' : 'error';
        } else {
          item.validateStatus = isValidMin || isValidMax ? 'success' : 'error';
        }
        this.setState({});
      }
      return;
    }
    if (dataIndex) {
      fieldsValue[dataIndex] = e;
    }
    if (callBackDataIndex.indexOf('reset=') > -1) { // 根据选择的下拉框数据重置其他相关类型的值
      callBack && callBack(e, dataIndex, fieldsValue);
      let dataIndexObj = callBackDataIndex.split('=')[1] ? JSON.parse(callBackDataIndex.split('=')[1]) : {};
      for (var key in dataIndexObj) {
        if (dataIndexObj[key] === '') {
          dataIndexObj[key] = undefined;
        }
      }
      this.props.form.setFieldsValue({
        ...dataIndexObj
      })
      return;
    }
    let result = callBack && callBack(fieldsValue, e, dataIndex);
    result.then((res) => {
      this.state[callBackDataIndex] = res;
      this.setState({});
    })
  }

  // 获取表单中的某个字段的值
  getFieldValue = (dataIndex) => {
    let value = '';
    if (dataIndex) {
      value = this.props.form.getFieldValue(dataIndex);
    }
    return value;
  }

  // 获取表单值 - isGetDesc(是否获取对应描述数据)
  getFieldsValue = (isGetDesc) => {
    const { rangeParams, otherInfo } = this.state;
    let values = this.formDataFormatConversion(this.props.form.getFieldsValue(), isGetDesc);
    return { ...values, ...rangeParams, ...otherInfo };
  }

  // 用于循环中调用 - 遍历选择表单数据
  getPromiseFieldsValue = (isGetDesc) => {
    return new Promise((resolve, reject) => {
      let fieldsValue = this.getFieldsValue(isGetDesc);
      resolve(fieldsValue);
    })
  }

  handleSave = () => {
    try {
      const { rangeParams, filterFormData, otherInfo } = this.state;
      return new Promise((resolve, reject) => {
        this.props.form.validateFields((err, values) => {
          console.log('values', JSON.parse(JSON.stringify(values)))
          if (!err) {
            let currentTitle = '';
            for (let i = 0; i < filterFormData.length; i++) {
              if (filterFormData[i].typeCode === 'RangePicker' && filterFormData[i].required === 'Y') {
                // let currentDataIndexArr = filterFormData[i].dataIndex && filterFormData[i].dataIndex.indexOf('^') > -1 ? filterFormData[i].dataIndex.split('^') : ['startDate', 'endDate'];
                // 日期范围必填只判断开始日期
                let currentDataIndexArr = filterFormData[i].dataIndex && filterFormData[i].dataIndex.indexOf('^') > -1 ? [filterFormData[i].dataIndex.split('^')[0]] : ['startDate'];
                for (let j = 0; j < currentDataIndexArr.length; j++) {
                  if (!(rangeParams[currentDataIndexArr[j]])) {
                    currentTitle = filterFormData[i].title;
                    break;
                  }
                }
              }
            }
            if (currentTitle) { // 日期范围必填验证
              resolve({ error: true, errorMessage: '【' + currentTitle + '】开始日期不能为空！' });
            } else {
              resolve({
                ...this.getDataIndexValues(),
                ...this.formDataFormatConversion(values, 'undefined'),
                ...rangeParams,
                ...otherInfo,
                error: false
              });
            }
          } else {
            resolve({ error: true });
          }
        });
      })
    } catch (error) {
      console.log(error)
    }
  }

  // 重置表单
  resetFields = () => {
    this.setState({ rangeParams: {}, otherInfo: {}, currentDataIndex: '', currentItemData: {} });
    this.props.form.resetFields(); //清空所有
  }

  // 表单数据格式转换 - 保存时
  formDataFormatConversion = (fieldsValues, nullFlag) => {
    let { rowData, filterFormData } = this.state;
    let nullVal = nullFlag === 'undefined' ? undefined : '';
    if (filterFormData && filterFormData.length > 0) {
      for (let i = 0; i < filterFormData.length; i++) {
        let checkboxArr = filterFormData[i]?.detailItem?.item || filterFormData[i]?.detailItem || [];
        for (let keys in fieldsValues) {
          if (filterFormData[i].dataIndex === keys) {
            fieldsValues[keys] = fieldsValues[keys] !== undefined ? fieldsValues[keys] : nullVal;
            if (filterFormData[i].typeCode === 'SearchSelect') {
              // 修改了取修改后的值，没修改返回原值
              let valID = filterFormData[i].valueID || filterFormData[i].methodName;
              let currentFieldsObj = Util.returnDataCccordingToAttributes(filterFormData[i].detailItem, fieldsValues[keys], (filterFormData[i]?.descindex || 'descripts'));
              fieldsValues[valID] = (filterFormData[i] && filterFormData[i].oldValueindex ? currentFieldsObj[filterFormData[i].oldValueindex] : currentFieldsObj[valID]) || (currentFieldsObj?.id || rowData[valID]);
            } else if (filterFormData[i].typeCode === 'Switch' || ((filterFormData[i].typeCode === 'Checkbox' || filterFormData[i].typeCode === 'CheckBox') && !(checkboxArr && checkboxArr.length > 0))) { // 开关
              fieldsValues[keys] = fieldsValues[keys] ? 'Y' : 'N';
            } else if (filterFormData[i].typeCode === 'DatePicker' || filterFormData[i].typeCode === 'Date' || filterFormData[i].typeCode === 'DateTime') {
              if (filterFormData[i].showTime || filterFormData[i].typeCode === 'DateTime') {
                fieldsValues[keys] = fieldsValues[keys] ? moment(fieldsValues[keys]).format('YYYY-MM-DD HH:mm:ss') : nullVal; // 日期时间
              } else {
                fieldsValues[keys] = fieldsValues[keys] ? moment(fieldsValues[keys]).format('YYYY-MM-DD') : nullVal; // 日期
              }
            } else if (filterFormData[i].typeCode === 'Time') { // 时间
              fieldsValues[keys] = fieldsValues[keys] ? moment(fieldsValues[keys]).format('HH:mm:ss') : nullVal;
            } else if (filterFormData[i].typeCode === 'Select' && nullFlag !== 'N' && filterFormData[i].mode !== 'multiple') { // 获取下拉框对应的描述
              let descCode = keys && keys.indexOf('ID') > -1 ? keys.replace('ID', 'Desc') : (keys + 'Desc');
              fieldsValues[descCode] = Util.returnDataCccordingToAttributes(filterFormData[i].detailItem, fieldsValues[keys])?.descripts || nullVal;
            }
          }
        }
      }
    }
    return fieldsValues;
  }

  // 表单数据转换 - 使用
  formDataConversion = fieldsValues => {
    let { filterFormData } = this.state;
    if (filterFormData && filterFormData.length > 0) {
      for (let i = 0; i < filterFormData.length; i++) {
        let checkboxArr = filterFormData[i]?.detailItem?.item || filterFormData[i]?.detailItem || [];
        for (let keys in fieldsValues) {
          if (filterFormData[i].dataIndex === keys) {
            // fieldsValues[keys] = typeof (fieldsValues[keys]) === 'number' ? String(fieldsValues[keys]) : fieldsValues[keys];
            if (filterFormData[i].typeCode === 'Switch' || ((filterFormData[i].typeCode === 'Checkbox' || filterFormData[i].typeCode === 'CheckBox') && !(checkboxArr && checkboxArr.length > 0))) { // 开关
              fieldsValues[keys] = fieldsValues[keys] === 'Y' ? true : false;
            } else if (filterFormData[i].typeCode === 'DatePicker' || filterFormData[i].typeCode === 'Date' || filterFormData[i].typeCode === 'DateTime') {
              if (filterFormData[i].showTime || filterFormData[i].typeCode === 'DateTime') {
                fieldsValues[keys] = fieldsValues[keys] && !(moment.isMoment(fieldsValues[keys])) ? moment(fieldsValues[keys], 'YYYY-MM-DD HH:mm:ss') : fieldsValues[keys]; // 日期时间
              } else {
                fieldsValues[keys] = fieldsValues[keys] && !(moment.isMoment(fieldsValues[keys])) ? moment(fieldsValues[keys], 'YYYY-MM-DD') : fieldsValues[keys]; // 日期
              }
            } else if (filterFormData[i].typeCode === 'Time') { // 时间
              fieldsValues[keys] = fieldsValues[keys] && !(moment.isMoment(fieldsValues[keys])) ? moment(fieldsValues[keys], 'HH:mm:ss') : fieldsValues[keys];
            } else if (filterFormData[i].typeCode === 'Select') { // 下拉框
              fieldsValues[keys] = fieldsValues[keys] && typeof (fieldsValues[keys]) === 'number' ? String(fieldsValues[keys]) : fieldsValues[keys];
            } else if (filterFormData[i].typeCode === 'UploadFile' || filterFormData[i].typeCode === 'UploadImg') { // 上传
              fieldsValues[keys] = fieldsValues[keys] && Array.isArray(fieldsValues[keys]) ? fieldsValues[keys] : [];
            }
          }
        }
      }
    }
    return fieldsValues
  }

  // 输入域列表展示change事件
  handleInputTableChang = e => {
    const { currentDataIndex } = this.state;
    if (!(e.target.value)) { // 为空时清除选择数据
      this.props.modalSelectClear && this.props.modalSelectClear(currentDataIndex);
    }
  }

  // 打开弹窗
  handleShowTableModal = (e, record) => {
    if (!e.target.value) {
      message.info('请输入别名回车搜索！');
      return;
    }
    let id = record?.dataIndex || '';
    let top = document.getElementById(id).getBoundingClientRect().top + 40 + 'px';
    let left = document.getElementById(id).getBoundingClientRect().left + 'px';
    this.setState({
      top,
      left,
      currentDataIndex: id, // 当前操作的输入域，一个表单中存在多个InputTable使用
      searchDesc: e.target.value, // 查询的别名
    }, () => {
      this.getModalListData('show');
    })
  }

  // 操作弹框
  onClickRowPublic = (record) => {
    return {
      onClick: () => {
        if (this.state.modalRowID === '') {
          // 保存行数据以及ID
          this.setState({ modalRowID: record.key })
        } else {
          if (this.state.modalRowID !== record.key) {
            this.setState({ modalRowID: record.key })
          }
        }
      },
      onDoubleClick: () => {
        this.confirmSelection(record);
      }
    }
  }

  setRowClassNamePublic = (record) => {
    return record.key === this.state.modalRowID ? 'clickRowStyle' : (record?.banFlag === 'Y' ? 'common-row-color-ff868c' : '');
  }

  // 双击选中行数据的回调
  confirmSelection = (record) => {
    const { currentDataIndex } = this.state;
    if (record?.banFlag === 'Y') {
      message.error(record?.banDesc || '改产品已停用！');
      return;
    }
    this.setState({ searchDesc: record.searchDesc }, () => {
      this.modalTableRef.handleCancel();
      this.props.modalConfirmSelect && this.props.modalConfirmSelect(record, currentDataIndex); // 双击选择回调返回行数据
    })
  }

  // 修改名称列表条数以及列数
  compilePage = (page, pageSize) => {
    this.setState({ page, pageSize }, () => {
      this.getModalListData();
    })
  }

  // 获取描述列表数据
  getModalListData = (isShow) => {
    const { filterFormData, page, pageSize, searchDesc, currentDataIndex } = this.state;
    let currentFormItem = Util.returnDataCccordingToAttributes(filterFormData, currentDataIndex, 'dataIndex');
    if (!(currentFormItem && 'className' in currentFormItem && currentFormItem.className)) return;
    this.setState({ modalTableLoading: true });
    let parentParams = (this.props.getModalTableParams && this.props.getModalTableParams()) || {};
    let data = {
      params: [{
        ...parentParams,
        [currentFormItem?.methodName || 'stockAlias']: searchDesc,
      }],
      pagination: [{
        pageSize: pageSize,
        currentPage: page
      }]
    }
    $http.post('urlS', this, {
      code: currentFormItem?.className || '',
      data: data,
      success: function (res) {
        if (res.errorCode === '0') {
          let modalTableData = res.result && 'rows' in res.result ? Util.addKeyValueToDataSource(res.result.rows) : Util.addKeyValueToDataSource(res.result);
          this.setState({ modalTableData, modalTotal: res.result?.total || 0, modalRowID: modalTableData && modalTableData.length > 0 ? modalTableData[0].key : '', modalTableLoading: false }, () => {
            isShow === 'show' ? this.modalTableRef.showModal() : '';
          })
        } else {
          this.setState({ modalTableData: [], modalTotal: 0, modalTableLoading: false });
          isShow === 'show' ? this.modalTableRef.showModal() : '';
        }
        setTimeout(() => {
          var gundong = document.getElementById('public-form-gundong');
          gundong && (gundong.scrollTop = 0);
        }, 100)
      },
      error: function () {
        this.setState({ modalTableData: [], modalTotal: 0, modalTableLoading: false });
        isShow === 'show' ? this.modalTableRef.showModal() : '';
      }
    })
  }

  // 键盘操作名称模态框数据
  handlePublicModalTableOnKeydown = (e) => {
    var e = window.event || e;
    let scroll_height = 26;
    let id = '';
    let oneArr = this.state.modalTableData && this.state.modalTableData.length > 0 ? this.state.modalTableData : [];
    switch (e.keyCode) {
      case 13:
        if (this.state.modalRowID) {
          let obj = {}
          for (var i = 0; i < oneArr.length; i++) {
            if (oneArr[i].key === this.state.modalRowID) {
              obj = i > 0 ? oneArr[i] : oneArr[0];
              break;
            }
          }
          this.confirmSelection(obj);
        } else {
          message.info('请选中一条数据操作');
        }
        break;
      case 38: //上
        if (this.state.modalRowID) {
          for (var i = 0; i < oneArr.length; i++) {
            if (oneArr[i].key === this.state.modalRowID) {
              id = i > 0 ? oneArr[i - 1].key : oneArr[0].key;
              break;
            }
          }
          this.setState({ modalRowID: id })
          setTimeout(() => {
            var gundong = document.getElementById('public-form-gundong');
            gundong && (gundong.scrollTop = gundong.scrollTop - scroll_height);
          }, 100)
        } else {
          this.setState({ modalRowID: oneArr[0].key })
        }
        break;
      case 40: //下
        if (this.state.modalRowID) {
          for (let i = 0; i < oneArr.length; i++) {
            if (oneArr[i].key === this.state.modalRowID) {
              id = i + 1 >= oneArr.length ? oneArr[oneArr.length - 1].key : oneArr[i + 1].key;
              break;
            }
          }
          this.setState({ modalRowID: id })
          setTimeout(() => {
            var gundong = document.getElementById('public-form-gundong');
            gundong && (gundong.scrollTop = gundong.scrollTop + scroll_height);
          }, 100)
        } else {
          this.setState({ modalRowID: oneArr[0].key })
        }
        break;
    }
  }

  // 打开表单数据维护弹窗
  showFromMaintenanceModal = (componentName) => {
    this.formDataMaintenanceRef && this.formDataMaintenanceRef.modifyVisible(true, componentName);
  }

  // 查询表单数据
  handleQueryFormData = () => {
    this.props.handleQueryFormData && this.props.handleQueryFormData();
  }

  // 下拉框关联取值
  handleSelectLinkChange = async (e, record, valType, rowData) => {
    try {
      let { filterFormData } = this.state;
      let recordDetailItem = record?.detailItem || [];
      let methodName = record?.methodName || ''; // 关联方法 - 存接口参数
      let linkCode = record?.linkCode || ''; // 关联取值接口代码
      let selectValues = Util.returnDataCccordingToAttributes(recordDetailItem, e, 'id');
      let linkValueCodeArr = record && 'linkValueCode' in record ? (Array.isArray(record.linkValueCode) ? record.linkValueCode : [record.linkValueCode]) : [];
      let clearValues = {};
      if (selectValues && 'inputType' in selectValues && selectValues.inputType) { // 关联切换输入框类型
        for (let i = 0; i < filterFormData.length; i++) {
          let currentIndex = i;
          let currentFormItem = filterFormData[i];
          if (linkValueCodeArr && Array.isArray(linkValueCodeArr) && linkValueCodeArr.indexOf(currentFormItem.dataIndex) > -1) {
            currentFormItem.typeCode = selectValues.inputType;
            clearValues[currentFormItem.dataIndex] = undefined;
            if (selectValues.inputType === 'SearchSelect') { // 远程搜索
              currentFormItem.trigger = selectValues?.trigger || (methodName && methodName.indexOf('trigger') > -1 ? Util.getValueByUrlStr(methodName, 'trigger') : 'Enter');; // 回车触发
              currentFormItem.valueindex = selectValues?.valueindex || (methodName && methodName.indexOf('valueIndex') > -1 ? Util.getValueByUrlStr(methodName, 'valueIndex') : 'id');
              currentFormItem.descindex = selectValues?.descindex || (methodName && methodName.indexOf('descIndex') > -1 ? Util.getValueByUrlStr(methodName, 'descIndex') : 'descripts');
              currentFormItem.valueindex = selectValues?.valueindex || (methodName && methodName.indexOf('valueIndex') > -1 ? Util.getValueByUrlStr(methodName, 'valueIndex') : 'descripts'); // 显示在界面上的值 -> 对应下拉数据返回的描述
              currentFormItem.valueID = selectValues?.valueID || (methodName && methodName.indexOf('valueID') > -1 ? Util.getValueByUrlStr(methodName, 'valueID') : 'id'); // 需要存到后台的字段对应的id值 - 关联方法
              currentFormItem.httpCode = selectValues?.httpCode || linkCode || '';
              currentFormItem.httpDescField = selectValues?.httpDescField || (methodName && methodName.indexOf('httpDescField') > -1 ? Util.getValueByUrlStr(methodName, 'httpDescField') : 'desc');
              currentFormItem.onSearch = (e) => this.handleChargeSearch(e, currentIndex, currentFormItem);
            }
          }
        }
      } else { // 关联下一个输入域获取数据
        let values = this.getFieldsValue('N');
        let data = {
          params: [{
            ...(valType === 'return' ? rowData : values),
            [record?.methodName || 'id']: e, // 可对应维护成关联方法
            [record?.dataIndex || record?.code]: e,
          }]
        }
        let res = await React.$asyncPost(this, linkCode, data);
        // 取单个数据的情况
        let detailItem = res.result && 'row' in res.result ? res.result.rows : (
          res.result && 'rows' in res.result && res.result.rows ? res.result.rows : (
            res.result && 'Data' in res.result && res.result.Data ? res.result.Data : (
              res.result && 'data' in res.result && res.result.data ? res.result.data : (res?.result || []))));
        let selectData = res && 'result' in res ? res.result : res;
        for (let i = 0; i < linkValueCodeArr.length; i++) {
          let linkTypeRecord = Util.returnDataCccordingToAttributes(filterFormData, linkValueCodeArr[i], 'code');
          if (linkTypeRecord?.typeCode === 'Select') {
            for (let j = 0; j < filterFormData.length; j++) {
              if (filterFormData[j].dataIndex === linkValueCodeArr[i]) {
                let currentDetailItem = linkValueCodeArr.length > 1 ? this.filterSelectData(selectData, linkValueCodeArr[i]) : detailItem;
                let currentDefaultVal = Util.returnDataCccordingToAttributes(currentDetailItem, 'Y', 'default')?.id;
                filterFormData[j].detailItem = currentDetailItem;
                clearValues[linkValueCodeArr[i]] = currentDefaultVal || undefined;
              }
            }
            if (linkTypeRecord && 'linkValueCode' in linkTypeRecord) { // 栗：选择省同时清除区
              if (linkTypeRecord.linkValueCode && Array.isArray(linkTypeRecord.linkValueCode)) { // 数组情况
                for (let k = 0; k < linkTypeRecord.linkValueCode.length; k++) {
                  clearValues[linkTypeRecord.linkValueCode[k]] = undefined;
                }
              } else {
                clearValues[linkTypeRecord.linkValueCode] = undefined;
              }
            }
          } else if (linkTypeRecord?.typeCode === 'Input' || linkTypeRecord?.typeCode === 'inputNumber' || linkTypeRecord?.typeCode === 'InputNumber') {
            let inputValue = typeof (selectData) === 'string' ? selectData : (selectData[record?.methodName || 'id'] || undefined);
            clearValues[linkValueCodeArr[i]] = inputValue;
          }
        }
      }
      this.setState({ filterFormData }, () => {
        if (JSON.stringify(clearValues) !== '{}' && valType !== 'return') { // 清除关联选择数据；栗：选择省清除市
          this.setFieldsValue(clearValues);
        }
      });
    } catch (error) {
      console.log(error);
    }
  }

  filterSelectData = (selectData, dataIndex) => {
    let detailItem = [];
    if (Object.prototype.toString.call(selectData) === '[object Object]') {
      for (let key in selectData) {
        if (dataIndex.indexOf(key) > -1) {
          detailItem = selectData[key];
          break;
        }
      }
    }
    return detailItem;
  }

  // 关闭数据展示抽屉
  handleDrawerClose = () => {
    this.setState({ drawerVisible: false }, () => {
      store.dispatch({
        type: 'DynamicRenderingForm_drawerVisible',
        value: false
      })
      store.dispatch({
        type: 'DynamicRenderingForm_diffActive',
        value: ''
      })
    });
  }

  // 数据对比选中查看
  handleDiffItemClick = (id, clickType) => {
    store.dispatch({
      type: 'DynamicRenderingForm_diffActive',
      value: id
    });
    if (clickType === 'formLabel') {
      let { diffData } = this.state;
      let currentIndex = 0;
      for (let i = 0; i < diffData.length; i++) {
        if (diffData[i].id === id) {
          currentIndex = i;
          break;
        }
      }
      // 跳转对对应的位置
      setTimeout(() => {
        var gundong = document.getElementById('drfd-content');
        if (gundong && gundong.scrollHeight) {
          let scrollTop = 98 * currentIndex;
          let currentScrollTop = gundong?.scrollTop || 0;
          if ((scrollTop + 98) >= (gundong?.offsetHeight || gundong?.clientHeight || 0) || (currentScrollTop > scrollTop)) {
            gundong.scrollTop = scrollTop;
          }
        }
      }, 100)
    }
  }

  // 病人id
  handlePatientChange = (e, item) => {
    if (!(e.target.value)) { // 为空时清除选择数据
      let className = item?.className || 'patID';
      this.state.otherInfo[className] = undefined;
      this.setState({});
    }
  }

  // 查询患者信息
  handlePatientSearch = async (value, item, index) => {
    try {
      let className = item?.className || 'patID';
      if (!value) {
        this.state.otherInfo[className] = undefined;
        this.setState({});
        return;
      };
      item.loading = true;
      this.setState({});
      let data = {
        params: [{
          number: value,
        }],
        pagination: [{
          pageSize: 100,
          currentPage: 1,
        }]
      }
      let res = await React.$asyncPost(this, '03030004', data);
      if (res.errorCode === '0') {
        let patData = res.result?.Data || [];
        if (patData && patData.length === 1) {
          let patID = patData[0]?.patID || '';
          this.state.otherInfo[className] = patID;
          this.setState({}, () => {
            this.props.handleQuery && this.props.handleQuery(this.state.patID, patData[0]);
          });
        } else if (patData && patData.length > 1) {
          this.setState({ currentItemData: { ...item, inputValue: value } }, () => {
            this.findPatientsRef && this.findPatientsRef.showModal();
            this.findPatientsRef && this.findPatientsRef.setValue(value);
          })
        } else {
          message.error('未查询到患者信息!');
        }
      }
    } catch (error) {
      console.log(error);
    }
    item.loading = false;
    this.setState({ currentItemData: {} });
  }

  // 确认选择改患者
  handlePatientInfoConfirm = (patientInfo) => {
    const { currentItemData } = this.state;
    let className = currentItemData?.className || 'patID';
    let patID = patientInfo?.patID || '';
    this.state.otherInfo[className] = patID;
    let linkMethod = currentItemData?.linkMethod || '';
    let fillingMethod = Util.getValueByUrlStr(linkMethod, 'fillingMethod'); // 填充方法
    if (fillingMethod !== 'none' || fillingMethod !== 'N') {
      this.setFieldsValue({ [currentItemData?.dataIndex || 'patNo']: fillingMethod ? patientInfo[fillingMethod] : patientInfo?.patNo || '' });
    }
    this.setState({}, () => {
      this.props.handleQuery && this.props.handleQuery(patID, patientInfo);
    })
  }

  render() {
    const { showPagination, modalTableComponentName, className, drawerWidth, stopFlag } = this.props;
    const { filterFormData, top, left, modalTableData, modalTableLoading, modalColumns, modalTotal, modalTotalWidth, drawerVisible, diffData, diffActive } = this.state;
    let param = {
      top,
      left,
      isOnRow: true,
      rowClassName: true,
      stopFlag: stopFlag || 'Y', // 停用标志
      showPagination: showPagination !== 'N' ? true : false,
      total: modalTotal,
      data: modalTableData,
      loading: modalTableLoading,
      componentName: modalTableComponentName,
      columns: modalColumns && modalColumns.length > 0 ? modalColumns : [],
      width: modalTotalWidth && parseInt(modalTotalWidth) > 1200 ? '1200px' : modalTotalWidth,
    };

    return (
      <div className="dynamic-rendering-form">
        <Form className={className || ''}>
          <Row>
            {filterFormData && Array.isArray(filterFormData) ? this.renderForm(filterFormData) : ''}
          </Row>
        </Form>
        <div
          tabIndex={1}
          onKeyDown={this.handlePublicModalTableOnKeydown}
          style={{ outline: 'none' }}
        >
          <PublicModalTable
            id="public-form-gundong"
            param={param}
            onRef={ref => this.modalTableRef = ref}
            compilePage={this.compilePage}
            getColumns={this.props?.getModalTableColumns || null}
            onClickRowPublic={this.onClickRowPublic}
            setRowClassNamePublic={this.setRowClassNamePublic}
          />
        </div>
        <PublicFormDataMaintenance handleQuery={this.handleQueryFormData} onRef={ref => this.formDataMaintenanceRef = ref} />
        <FileOnlinePreview onRef={ref => this.filePreviewRef = ref} />
        {/* 查询患者 */}
        <FindPatients handleParms={this.handlePatientInfoConfirm} OnChildrefs={ref => this.findPatientsRef = ref} />
        <Drawer
          title="数据差异对比"
          placement="right"
          mask={false}
          width={drawerWidth || 268}
          drawerStyle={{ paddingTop: '49px' }}
          headerStyle={{ padding: '12px 24px' }}
          bodyStyle={{ padding: '12px', paddingRight: '6px' }}
          onClose={this.handleDrawerClose}
          visible={drawerVisible}
          className="dynamic-rendering-form-drawer"
        >
          <div id="drfd-content" className="scroll-bar-style drfd-content" style={{ height: store.getState().tableHeight.y + 190 + 'px' }}>
            {diffData && Array.isArray(diffData) && diffData.map((item, index) => {
              let id = item?.id || ('drf_' + index)
              return (
                <div id={id} key={index} className={'drfd-item' + (diffActive === id ? ' drfd-item-active' : '')} onClick={() => this.handleDiffItemClick(id)}>
                  <div className="drfd-item-top-line"></div>
                  <div className="drfd-item-header">
                    <div className="drfd-item-header-title">
                      {item?.title || ''}
                    </div>
                  </div>
                  <div className="drfd-item-content">
                    <div>
                      原值：<span style={{ color: '#666' }}>{item?.old || ''}</span>
                    </div>
                    <div>
                      修改后：<span style={{ color: '#666' }}>{item?.new || ''}</span>
                    </div>
                  </div>
                </div>
              )
            })}
          </div>
        </Drawer>
      </div>
    )
  }
};

const CreateDynamicRenderingForm = Form.create()(DynamicRenderingForm);
export default CreateDynamicRenderingForm;